package com.yljk.yljkproject.rnmodule;

import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alsk.rn.kit.bridge.impl.im.KitImModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableMap;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.config.BaseConfig;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.network.https.interceptor.NetWorkUtils;
import com.yilijk.base.utils.ALog;
import com.yljk.servicemanager.constants.ConfigApi;
import com.yljk.servicemanager.constants.UrlApi;
import com.yljk.servicemanager.interfaceapi.NetWorkCallBack;
import com.yljk.yljkproject.immessageapl.HistoryApi;
import com.yljk.yljkproject.utils.EMMessageUtils;
import com.yljk.yljkproject.utils.ReactUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;

import java.util.List;
import java.util.Map;


/**
 * 原生提供给RN使用的IM方法
 * Android provide react-native im function
 */
public
class RNKitImModule extends KitImModule {

    private static final String TAG = "IMMessage";

    /**
     * 发送消息
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void sendMessage(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        EMMessageUtils.kitSendMsg(reactContext, readableMap, promise);
    }

    /**
     * 获取漫游数据
     *
     * @param reactContext
     * @param readableMap
     * @param promise
     */
    @Override
    public void getRoamingMessageList(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.d(TAG, "recallMessage: " + readableMap);
        String nativeMap = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
        Map map = (Map) JSON.parse(nativeMap);

        String to = "";
        int pageSize = 0;
        String messageId = "";
        if (map!=null){
             to = (String) map.get("to");//a3
             pageSize = (Integer)map.get("size");//15
             messageId = (String) map.get("messageId");//15
        }
        ALog.d(TAG, "getRoamingmessagebody: " + to);
        ALog.d(TAG, "getRoamingmessagebTHody: " + pageSize);
        ALog.e(TAG, "getRoamingmessagebTHody: " + readableMap);
        org.json.JSONObject jsonObject = null;
        try {
            if (nativeMap!=null){
                jsonObject = new org.json.JSONObject(nativeMap);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            if (jsonObject!=null && jsonObject.has("status")&&
                    jsonObject.getString("status").equals("5")){
                //漫游到问诊单
                int index= 0;
                while (true){
                    index++;
                    ALog.i(TAG, "getRoamingMessageList: "+index);
                    try {
                        EMCursorResult<EMMessage> cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(to, EMConversation.EMConversationType.Chat, index, null);
                        List<EMMessage> data = cursorResult.getData();
                        if (data.size()==0){
                            return;
                        }
                        EMMessage emMessage = data.get(0);

                        if (emMessage.getType() == EMMessage.Type.CUSTOM ){
                            EMCustomMessageBody body = (EMCustomMessageBody) emMessage.getBody();
                            if (!"patient_update_charges".equals(body.event())){
                                EMMessageUtils.history2Json(cursorResult, new HistoryApi() {
                                    @Override
                                    public void onSuccess(String maptoJson) {
                                        promise.resolve(maptoJson);
                                    }

                                    @Override
                                    public void onError(String failmsg) {

                                    }
                                });
                                break;
                            }
                        }
                        if (index == 20){
                            break;
                        }
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }

                }

            }else{
                EMClient.getInstance().chatManager().asyncFetchHistoryMessage(to, EMConversation.EMConversationType.Chat, pageSize, messageId, new EMValueCallBack<EMCursorResult<EMMessage>>() {
                    @Override
                    public void onSuccess(EMCursorResult<EMMessage> emMessageEMCursorResult) {
                        EMMessageUtils.history2Json(emMessageEMCursorResult, new HistoryApi() {
                            @Override
                            public void onSuccess(String maptoJson) {
                                promise.resolve(maptoJson);
                            }

                            @Override
                            public void onError(String failmsg) {

                            }
                        });

                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void recallMessage(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        ALog.i(TAG, "recallMessage: " + readableMap.toString());
        String to = readableMap.getString("to");
        String getMessageId = readableMap.getString("messageId");
        boolean imteam = false;
        if (readableMap.hasKey("imteam")){
            imteam = readableMap.getBoolean("imteam");
        }
//        String getMessageId = readableMap.getString("messageId");
        String readableMapString = ReactUtils.INSTANCE.delNativeMap(readableMap.toString());
        org.json.JSONObject jsonObject1 = null;
        try {
            if (readableMapString != null) {
                jsonObject1 = new org.json.JSONObject(readableMapString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String ext = null;
        if (jsonObject1 !=null && jsonObject1.has("ext")){
            try {
                ext = jsonObject1.getString("ext");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        int chargesListId = -1;
        if (ext!=null){
            try {
                org.json.JSONObject jsonObject2 = new org.json.JSONObject(ext);
                if (jsonObject2.has("chargesListId")){
                    chargesListId = jsonObject2.getInt("chargesListId");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        EMMessage recallmsg = EMMessage.createTxtSendMessage("1111", to);
        recallmsg.setMsgId(getMessageId);
        recallmsg.setTo(to);
        recallmsg.setStatus(EMMessage.Status.SUCCESS);
        try {
            //撤回消息
            EMClient.getInstance().chatManager().recallMessage(recallmsg);
            ALog.i(TAG, "recallMessage: "+recallmsg.getMsgId());
            //拉取漫游
            EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager()
                    .fetchHistoryMessages(to, EMConversation.EMConversationType.Chat, 1, null);
            EMMessage emMessage = emMessageEMCursorResult.getData().get(0);
            ALog.i(TAG, "recallMessage: "+emMessage);

            Intent intent = new Intent(BaseConfig.Receiver.BroadcastReceiver);
            intent.putExtra(ConfigApi.refreshRecall, true);         //向广播接收器传递数据
            intent.putExtra(ConfigApi.recallMessage, 1);         //向广播接收器传递数据
            intent.putExtra(ConfigApi.receiverUser, to);         //向广播接收器传递数据
            reactContext.sendBroadcast(intent);      //发送广播
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", true);
            jsonObject.put("msg", "撤消成功");
            ALog.i(TAG, "onSuccess: " + jsonObject.toJSONString());
            promise.resolve(jsonObject.toJSONString());

            RequestParams params = new RequestParams();
            params.put("msgId",getMessageId);
            params.put("chargesListId",chargesListId);
            HttpUtils.post(UrlApi.cancel, params, new HttpCallBack<String>() {
                @Override
                public void onSuccess(String result, int code) {

                }

                @Override
                public void onFailure(String failureMsg, int statusCode) {

                }
            });

        } catch (HyphenateException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result", false);
            jsonObject.put("msg", "撤消失败");
            ALog.i(TAG, "HyphenateException: " + jsonObject.toJSONString());
            promise.resolve(jsonObject.toJSONString());
            e.printStackTrace();
        }


    }

    @Override
    public void sendGroupMessage(@NotNull ReactContext reactContext, @NotNull ReadableMap readableMap, @NotNull Promise promise) {
        EMMessageUtils.kitSendMsg(reactContext, readableMap, promise);
    }
}
